<template>    
  <div>    
    <h2>Todolist</h2>    
    <input type="text" v-model="newItem" @keyup.enter="addTodo" placeholder="回车添加待办事项" />    
    <ul>    
      <li v-for="(todo, index) in todos" :key="index">    
        <input type="checkbox" v-model="todo.done" />    
        <span :class="{ 'done-text': todo.done }">{{ todo.text }}</span>    
        <button @click="removeTodo(index)">删除</button>    
      </li>    
    </ul>    
  </div>    
</template> 
  
<script>  
export default {   
  data() {  
    return {  
      newItem: '',
      todos: []
    };  
  },
  computed:{
    getNewTodos() {
      return this.todos
    }
  },
  methods: {  
    addTodo() {  
      if (this.newItem.trim()) {  
        this.todos = [...this.todos, { text: this.newItem, done: false }]
        this.newItem = '';
        this.saveTodosToLocalStorage();
      }  
    },  
    removeTodo(index) {
      this.todos =  this.todos.filter((_, i) => i !== index)
    },  
    loadTodosFromLocalStorage() {  
      const savedTodos = localStorage.getItem('todos');  
      try {  
        if (savedTodos) {  
          this.todos = JSON.parse(savedTodos);  
        }  
      } catch (error) {  
        console.error('Error parsing todos from local storage:', error);  
      }  
    },  
    saveTodosToLocalStorage() {  
      localStorage.setItem('todos', JSON.stringify(this.getNewTodos));
    }  
  },  
  created() {  
    this.loadTodosFromLocalStorage();  
  },   
}  
</script>

<style scoped>
ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin-bottom: 10px;
}

input[type="text"] {
  margin-bottom: 10px;
  width: 200px;
}
.done-text {  
  text-decoration: line-through;  
} 

</style>